<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <h3 v-if="level1.length === 0">对不起，找不到相关文档!</h3>
      <a-row v-if="level1.length > 0">
        <a-col :span="6">
          <a-tree
              :tree-data="level1"
              @select="onSelect"
              :replaceFields="{ title: 'name', key: 'id', value: 'id' }"
              :defaultExpandAll="true"
              :defaultSelectedKeys="defaultSelectedKeys"
          >
          </a-tree>
        </a-col>
        <a-col :span="18" v-if="currentDoc">
          <div>
            <h2>{{ currentDoc.name }}</h2>
            <div>
              <span>阅读数：{{ currentDoc.viewCount || 0 }}</span> &nbsp; &nbsp;
              <span>点赞数：{{ currentDoc.voteCount || 0 }}</span>
            </div>
            <a-divider style="height: 2px; background-color: #9999cc" />
          </div>
          <div class="wangeditor" v-if="html" :innerHTML="html" />
          <div class="vote-div" v-if="currentDoc.id">
            <a-button type="primary" shape="round" :size="'large'" @click="vote" style="height: 55px">
              <template #icon>
                <LikeOutlined /> &nbsp;点赞：{{ currentDoc.voteCount || 0 }}
              </template>
            </a-button>
          </div>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';
import { Tool } from "@/utils/tool";
import { useRoute } from "vue-router";
import { LikeOutlined } from '@ant-design/icons-vue';

onMounted(() => {
  handleQuery();
});

const route = useRoute();
const docs = ref([]);
const html = ref('');
const defaultSelectedKeys = ref([] as number[]);
const level1 = ref([] as any[]); // 一级文档树，children属性为二级文档

// 使用计算属性确保currentDoc为非空对象
const currentDoc = computed(() => doc.value || {});
const doc = ref({} as any);

/**
 * 数据查询
 */
const handleQuery = () => {
  axios.get(`http://localhost:8080/obwiki/doc/all/${route.query.ebookId}`)
    .then((response) => {
      const data = response.data;
      if (data.success) {
        docs.value = data.content;
        level1.value = Tool.array2Tree(docs.value, 0);
        
        // 安全获取第一个节点
        const firstNode = level1.value[0] || {};
        if (firstNode.id) {
          defaultSelectedKeys.value = [firstNode.id];
          handleQueryContent(firstNode.id);
          doc.value = firstNode;
        }
      } else {
        message.error(data.message);
      }
    })
    .catch((error) => {
      console.error('查询文档失败', error);
      message.error('查询文档失败，请重试');
    });
};

/**
 * 内容查询
 */
const handleQueryContent = (id: number) => {
  axios.get(`http://localhost:8080/obwiki/content/findContent/${id}`)
    .then((response) => {
      const data = response.data;
      if (data.success) {
        html.value = data.content || '';
      } else {
        message.error(data.message);
      }
    })
    .catch((error) => {
      console.error('查询内容失败', error);
      message.error('查询内容失败，请重试');
    });
};

const onSelect = (selectedKeys: any[], info: any) => {
  console.log('selected', selectedKeys, info);
  if (selectedKeys.length > 0 && info.selectedNodes && info.selectedNodes.length > 0) {
    const selectedNode = info.selectedNodes[0] || {};
    doc.value = selectedNode;
    if (selectedKeys[0]) {
      handleQueryContent(selectedKeys[0]);
    }
  }
};

/**
 * 点赞功能
 */
const vote = () => {
  const docId = currentDoc.value.id;
  if (!docId) {
    message.warning('文档ID不存在，无法点赞');
    return;
  }
  
  axios.get(`http://localhost:8080/obwiki/doc/vote/${docId}`)
    .then((response) => {
      const data = response.data;
      if (data.success) {
        doc.value.voteCount = (doc.value.voteCount || 0) + 1;
      } else {
        message.error(data.message);
      }
    })
    .catch((error) => {
      console.error('点赞失败', error);
      message.error('点赞失败，请重试');
    });
};
</script>

<style>
/* wangeditor默认样式，参照: http://www.wangeditor.com/doc/pages/02-%E5%86%85%E5%AE%B9%E5%A4%84%E7%90%86/03-%E8%8E%B7%E5%8F%96html.html */
.wangeditor table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.wangeditor table td,
.wangeditor table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.wangeditor table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}
.wangeditor blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}
.wangeditor code {
  display: inline-block;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.wangeditor pre code {
  display: block;
}
.wangeditor ul, ol {
  margin: 10px 0 10px 20px;
}
.wangeditor blockquote p {
  font-family: "YouYuan";
  margin: 20px 10px !important;
  font-size: 16px !important;
  font-weight: 600;
}
.vote-div {
  padding: 15px;
  text-align: center;
}
.wangeditor img {
  max-width: 100%;
  height: auto;
}
.wangeditor iframe {
  width: 100%;
  height: 400px;
}
</style>